var isline

function get_state (){
  fetch('/get_state')
    .then(response => response.json())  // 解析JSON
    .then(data => {
      console.log('后端数据：', data);
      // 更新电梯状态标签
      if (data.escalator.state === "work") {
        elevatorStatusText.textContent = '运行中';
        elevatorStatusText.className = 'px-3 py-1 bg-success/10 text-success text-xs rounded-full';
      } else if (data.escalator.state === "IDLE") {
        elevatorStatusText.textContent = '待命';
        elevatorStatusText.className = 'px-3 py-1 bg-primary/10 text-primary text-xs rounded-full';
      } 
      if (data.escalator.door === "open") { 
        if (elevatorState.doorsOpen === false) {
            openDoors()
        }
      } else if (data.escalator.door === "close"){
        if (elevatorState.doorsOpen === true) {
            closeDoors();
        }
      }
      if (data.escalator.floor != elevatorState.currentFloor) {
        requestFloor(data.escalator.floor);
      }
      isline = true
      for (let i = 0; i < robotsData.length; i++) {
        // 可通过 break 中断循环，continue 跳过当前元素
        Object.keys(data.robots).forEach(key => {
          console.log(`键：${key}，值：${data.robots[key]}`);
          // 示例：满足条件时中断循环
          if (robotsData[i].id === key) {
            isline = false
            // robotsData[i].id = data.robots[key].id;
            robotsData[i].currentStatus = data.robots[key].currentStatus;
            robotsData[i].status = "online";
          }
        });
        if (isline){
          robotsData[i].status = "offline"
        }
      }
      
    })
    .catch(error => console.error('请求失败：', error));
}

// 1. 封装请求函数
const fetchSensorData = async () => {
    try {
        const response = await get_state();
        return response
    } catch (error) {
        console.error('请求失败：', error);
        return null;
    }
};

let pollInterval;
const startPolling = () => {
    // 定时执行
    pollInterval = setInterval(async () => {
        const data = await fetchSensorData();
    }, 200);  // 2秒间隔，可根据需求调整
};

// 4. 页面加载时启动，关闭时清理
window.onload = startPolling;
window.onunload = () => clearInterval(pollInterval);